
package de.fhhof.brst.lottery;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import de.fhhof.brst.dao.EventDAO;
import de.fhhof.brst.dao.HibernateEventDAO;
import de.fhhof.brst.data.Booking;
import de.fhhof.brst.data.Event;
import de.fhhof.brst.data.Ticket;
public class Lottery implements Serializable {
  /**
   * 
   */
  private static final long serialVersionUID =  3231824968185550786L;

  private de.fhhof.brst.dao.EventDAO eventDAO =  HibernateEventDAO.getHibernateEventDAO();

  public String start(de.fhhof.brst.data.Event event) {
		List<Booking> allBookings = eventDAO.getAllBookings(event.getId());
		List<Booking> wonBookings = new ArrayList<Booking>();

		long total = event.getAvailableTickets();
		
		if (total > allBookings.size()) total = allBookings.size();
		
		Ticket ticket;
		Booking booking;

		Collections.shuffle(allBookings);

		for (int j = 0; j < total; j++) {
			wonBookings.add(allBookings.get(j));
		}
		
		for (int i = 0; i < allBookings.size(); i++) {
			eventDAO.deleteBooking(allBookings.get(i));
		}
		
		for(int i = 0; i < wonBookings.size(); i++) {
			booking = wonBookings.get(i);
			ticket = new Ticket();
			ticket.setCustomer_id(booking.getUser_id());
			ticket.setEvent_id(booking.getEvent_id());
			ticket.setPrice(event.getPricePerTicket());
			eventDAO.saveTicket(ticket);
		}
		
		event.setLotteryStarted(true);
		eventDAO.editEvent(event);
		
		return "/events_frame.xhtml?faces-redirect=true";
  }

}
